<template>
  <div>

    <v-card>
      <v-card-title>
        <span class="title">{{`所有投票`}}</span>
        <v-spacer></v-spacer>
        <v-btn v-if="enableManage" color="primary" @click.native.stop="addVoteDialog = true">{{$t('vote.addItem')}}<v-icon right dark>add_circle_outline</v-icon></v-btn>
      </v-card-title>
      <v-divider></v-divider>
      <v-data-table
        :items="votes"
        :pagination.sync="pagination"
        :total-items="totalItems"
        :loading="loading"
        class="elevation-3"
        item-key="_id"
        hide-headers
      >
        <template slot="items" slot-scope="props">
          <tr>
            <td class="px-0">
              <v-list two-line>
                <v-list-tile>
                  <v-list-tile-content>
                    <v-list-tile-title>
                      <span @click="seeMore(props.item._id)" style="cursor: pointer">{{props.item.title}}</span>
                    </v-list-tile-title>
                    <v-list-tile-sub-title>
                      <v-icon color="blue" v-if="props.item.type === 1">radio_button_checked</v-icon>
                      <v-icon color="green" v-if="props.item.type === 2">check_box</v-icon>
                      {{props.item.type === 1 ? '单选' : '多选'}}
                    </v-list-tile-sub-title>
                  </v-list-tile-content>
                  <v-list-tile-action>
                    <span class="grey--text">{{props.item.created_at | formatTime}}</span>
                    <v-btn icon v-if="enableManage" @click="handleResult(props.item)"><v-icon color="secondary">flag</v-icon></v-btn>
                  </v-list-tile-action>
                </v-list-tile>
              </v-list>
            </td>
          </tr>
        </template>

      </v-data-table>
    </v-card>

    <v-dialog
      v-model="addVoteDialog"
      fullscreen
      transition="dialog-bottom-transition"
      :overlay="false"
      scrollable
    >
      <v-card tile>
        <v-toolbar card dark color="primary">
          <v-btn icon @click.native="addVoteDialog = false" dark>
            <v-icon>close</v-icon>
          </v-btn>
          <v-toolbar-title>{{ $t('vote.addItem') }}</v-toolbar-title>
        </v-toolbar>
        <v-card-text>
          <v-form>
            <v-text-field
              label="标题"
              v-model="newItem.title"
            ></v-text-field>
            <v-radio-group v-model="newItem.type" label="投票类型设置">
              <v-radio label="单选" :value="1"></v-radio>
              <v-radio label="多选" :value="2"></v-radio>
            </v-radio-group>
            <v-radio-group v-model="newItem.secret" label="投票结果设置">
              <v-radio label="公开结果" :value="false"></v-radio>
              <v-radio label="隐藏结果" :value="true"></v-radio>
            </v-radio-group>
            <dynamic-tags-input label="候选项（编辑后按回车键添加）" :chips.sync="newItem.options"></dynamic-tags-input>
          </v-form>
          <v-btn class="primary mt-4" large @click="handlePublish">确认发布</v-btn>
        </v-card-text>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
  import DynamicTagsInput from '@/components/DynamicTagsInput'
  import { fetchAllVotes, publishVote, fetchAllBuckets } from '@/api/vote'
  export default {
    components: { DynamicTagsInput },
    data() {
      return {
        votes: [],
        totalItems: 0,
        loading: false,
        pagination: {
          page: 1,
          rowsPerPage: 10
        },
        newItem: {
          title: '',
          type: 1,
          secret: false,
          options: ['选项1', '选项2', '选项3']
        },
        addVoteDialog: false
      }
    },
    watch: {
      pagination: {
        handler() {
          this.getDataFromApi()
        },
        deep: true
      }
    },
    computed: {
      enableManage() {
        return this.$store.getters.roles.some(v => (v === 'admin' || v === 'vote'))
      }
    },
    mounted() {
      this.getDataFromApi()
    },
    methods: {
      $_vote_checkNull() {
        return this.newItem.title && this.newItem.length !== 0
      },
      seeMore(voteId) {
        this.$router.push({ path: `/vote/detail/${voteId}` })
      },
      handleResult(vote) {
        // this.$router.push({ path: `/vote/buckets/${voteId}` })
        const tableHeaders = ['用户名', ...vote.options, '投票时间']
        fetchAllBuckets(vote._id).then(res => {
          const tableData = res.data.items.map(item => {
            const row = []
            row.push(item.voter.username)
            vote.options.forEach(label => {
              if (item.data.indexOf(label) >= 0) row.push(1)
              else row.push(0)
            })
            row.push(item.created_at)
            return row
          })
          import('@/vendor/Export2Excel').then(excel => {
            excel.export_json_to_excel(tableHeaders, tableData, vote.title)
            this.$notify.success('excel导出成功')
          })
        })
      },
      getDataFromApi() {
        this.loading = true
        const { page, rowsPerPage } = this.pagination
        fetchAllVotes(this.$store.getters.team, page, rowsPerPage).then(res => {
          this.votes = res.data.items
          this.totalItems = res.data.total
          this.loading = false
        })
      },
      handlePublish() {
        if (!this.$_vote_checkNull()) return this.$notify.warning('请填写完整')
        publishVote(this.newItem).then(res => {
          if (res.status === 200) {
            this.votes.unshift(res.data)
            this.totalItems++
            this.addVoteDialog = false
            this.$notify.success('发布成功')
            this.newItem.title = ''
            this.newItem.options = []
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
